<!--
/**
 * AnnotationList 组件
 * 
 * 标注列表组件，显示和管理标注数据
 * 
 * @author yangzhixin
 */
-->

<template>
  <div class="annotation-list">
    <!-- 标题和操作 -->
    <div class="list-header">
      <span class="list-title">标注列表</span>
      <q-badge :label="annotations.length" color="primary" />
      <q-space />
      <q-btn
        icon="delete_sweep"
        flat
        dense
        round
        :disable="annotations.length === 0"
        @click="handleClearAll"
      >
        <q-tooltip>清除所有</q-tooltip>
      </q-btn>
      <q-btn
        icon="download"
        flat
        dense
        round
        :disable="annotations.length === 0"
        @click="handleExport"
      >
        <q-tooltip>导出标注</q-tooltip>
      </q-btn>
    </div>

    <!-- 过滤器 -->
    <div v-if="showFilter" class="list-filter">
      <q-select
        v-model="filterTool"
        :options="toolOptions"
        label="工具类型"
        outlined
        dense
        clearable
        options-dense
        class="filter-select"
      />
      <q-input
        v-model="filterLabel"
        label="标签"
        outlined
        dense
        clearable
        class="filter-input"
      />
    </div>

    <!-- 标注列表 -->
    <div class="list-content">
      <!-- 空状态 -->
      <div v-if="filteredAnnotations.length === 0" class="empty-state">
        <q-icon name="label_off" size="48px" color="grey-5" />
        <p>{{ annotations.length === 0 ? '暂无标注' : '未找到匹配的标注' }}</p>
      </div>

      <!-- 列表 -->
      <q-list v-else bordered separator>
        <q-item
          v-for="(annotation, index) in filteredAnnotations"
          :key="annotation.annotationUID"
          clickable
          v-ripple
          :active="selectedAnnotations.includes(annotation.annotationUID)"
          @click="handleSelectAnnotation(annotation.annotationUID)"
        >
          <q-item-section avatar>
            <q-icon :name="getToolIcon(annotation.toolName)" color="primary" />
          </q-item-section>

          <q-item-section>
            <q-item-label>
              {{ getToolLabel(annotation.toolName) }}
            </q-item-label>
            <q-item-label caption>
              {{ annotation.metadata?.label || `标注 ${index + 1}` }}
            </q-item-label>
            <q-item-label v-if="annotation.metadata?.description" caption>
              {{ annotation.metadata.description }}
            </q-item-label>
          </q-item-section>

          <q-item-section v-if="showTimestamp" side>
            <q-item-label caption>
              {{ formatTimestamp(annotation.metadata?.createdAt) }}
            </q-item-label>
          </q-item-section>

          <q-item-section side>
            <div class="annotation-actions">
              <q-btn
                icon="edit"
                flat
                dense
                round
                size="sm"
                @click.stop="handleEditAnnotation(annotation)"
              >
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn
                icon="delete"
                flat
                dense
                round
                size="sm"
                color="negative"
                @click.stop="handleDeleteAnnotation(annotation.annotationUID)"
              >
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </div>
          </q-item-section>
        </q-item>
      </q-list>
    </div>

    <!-- 统计信息 -->
    <div v-if="showStats && annotations.length > 0" class="list-stats">
      <div class="stat-item">
        <span class="stat-label">总计:</span>
        <span class="stat-value">{{ stats.total }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">已选:</span>
        <span class="stat-value">{{ selectedAnnotations.length }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import type { Annotation } from '@/composables/useAnnotations';

/**
 * 组件属性
 */
interface Props {
  /** 标注列表 */
  annotations?: Annotation[];
  /** 选中的标注 */
  selectedAnnotations?: string[];
  /** 是否显示过滤器 */
  showFilter?: boolean;
  /** 是否显示时间戳 */
  showTimestamp?: boolean;
  /** 是否显示统计 */
  showStats?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  annotations: () => [],
  selectedAnnotations: () => [],
  showFilter: true,
  showTimestamp: true,
  showStats: true,
});

/**
 * 组件事件
 */
interface Emits {
  (e: 'select', annotationUID: string): void;
  (e: 'edit', annotation: Annotation): void;
  (e: 'delete', annotationUID: string): void;
  (e: 'clear-all'): void;
  (e: 'export'): void;
}

const emit = defineEmits<Emits>();

// 过滤器
const filterTool = ref<string | null>(null);
const filterLabel = ref('');

// 工具选项（用于过滤）
const toolOptions = computed(() => {
  const tools = new Set(props.annotations.map((a) => a.toolName));
  return Array.from(tools).map((tool) => ({
    label: getToolLabel(tool),
    value: tool,
  }));
});

// 过滤后的标注
const filteredAnnotations = computed(() => {
  let result = props.annotations;

  // 工具类型过滤
  if (filterTool.value) {
    result = result.filter((a) => a.toolName === filterTool.value);
  }

  // 标签过滤
  if (filterLabel.value) {
    const searchTerm = filterLabel.value.toLowerCase();
    result = result.filter((a) => {
      const label = a.metadata?.label?.toLowerCase() || '';
      const description = a.metadata?.description?.toLowerCase() || '';
      return label.includes(searchTerm) || description.includes(searchTerm);
    });
  }

  return result;
});

// 统计信息
const stats = computed(() => ({
  total: props.annotations.length,
  byTool: props.annotations.reduce((acc, a) => {
    acc[a.toolName] = (acc[a.toolName] || 0) + 1;
    return acc;
  }, {} as Record<string, number>),
}));

/**
 * 获取工具图标
 */
const getToolIcon = (toolName: string): string => {
  const iconMap: Record<string, string> = {
    Length: 'straighten',
    Angle: 'show_chart',
    RectangleROI: 'crop_square',
    EllipticalROI: 'panorama_fish_eye',
    CircleROI: 'radio_button_unchecked',
    ArrowAnnotate: 'arrow_forward',
    Probe: 'colorize',
    FreehandROI: 'gesture',
    Bidirectional: 'swap_horiz',
    default: 'label',
  };

  return iconMap[toolName] || iconMap.default;
};

/**
 * 获取工具标签
 */
const getToolLabel = (toolName: string): string => {
  const labelMap: Record<string, string> = {
    Length: '长度测量',
    Angle: '角度测量',
    RectangleROI: '矩形ROI',
    EllipticalROI: '椭圆ROI',
    CircleROI: '圆形ROI',
    ArrowAnnotate: '箭头标注',
    Probe: '探针',
    FreehandROI: '手绘ROI',
    Bidirectional: '双向测量',
  };

  return labelMap[toolName] || toolName;
};

/**
 * 格式化时间戳
 */
const formatTimestamp = (timestamp?: string): string => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

/**
 * 处理选择标注
 */
const handleSelectAnnotation = (annotationUID: string) => {
  emit('select', annotationUID);
};

/**
 * 处理编辑标注
 */
const handleEditAnnotation = (annotation: Annotation) => {
  emit('edit', annotation);
};

/**
 * 处理删除标注
 */
const handleDeleteAnnotation = (annotationUID: string) => {
  emit('delete', annotationUID);
};

/**
 * 处理清除所有
 */
const handleClearAll = () => {
  emit('clear-all');
};

/**
 * 处理导出
 */
const handleExport = () => {
  emit('export');
};
</script>

<style scoped lang="scss">
.annotation-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.list-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;

  .list-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }
}

.list-filter {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #e0e0e0;

  .filter-select,
  .filter-input {
    flex: 1;
  }
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 32px;
  text-align: center;

  p {
    margin-top: 12px;
    color: #666;
    font-size: 14px;
  }
}

.annotation-actions {
  display: flex;
  gap: 4px;
}

.list-stats {
  display: flex;
  gap: 16px;
  padding: 12px 16px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;

  .stat-item {
    display: flex;
    gap: 8px;
    font-size: 12px;

    .stat-label {
      color: #666;
    }

    .stat-value {
      color: #333;
      font-weight: 500;
    }
  }
}
</style>





